package controller

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"time"
	"traffic/system"
	"traffic/utils"

	"github.com/garyburd/redigo/redis"
)

func Save(r *http.Request, ad_id, ruleid, rule_memo, ip, visit, client string) int64 {
	var ip_zone, country, city, badip, ua string
	// log.Println("store.go 14:", visit)
	//	times := time.Now().Unix()
	//	times := time.Now().Format("2006-01-02 15:04:05")
	times := time.Now().Format("2006-01-02 15:04:05")
	url := r.Host + r.RequestURI

	publisher_id := r.FormValue("publisher_id")

	refer := r.Referer()
	ua = r.UserAgent()
	ip_int := utils.Ip2long(ip)
	ip_count := CountIP(ip_int)
	if ip_count > 0 {
		badip = "1"
	} else {
		badip = "0"
	}

	ipinfo := GetIpinfo(ip_int)
	if len(ipinfo) > 0 {
		ip_zone = ipinfo["timezone"].(string)
		country = ipinfo["country_code"].(string)
		city = ipinfo["city_name"].(string)
	}

	db := system.Db
	date := time.Now().Format("2006-01-02")
	TableName := "ads_traffic_" + date
	TableSql := "CREATE TABLE if not exists `" + TableName + "` (" +
		"`id` int(11) NOT NULL AUTO_INCREMENT," +
		"`ad_id` int(11) NOT NULL DEFAULT '0'," +
		"`publisher_id` varchar(255) NOT NULL DEFAULT ''," +
		"`rules_id` int(11) NOT NULL DEFAULT '0'," +
		"`rule_memo` varchar(50) NOT NULL DEFAULT ''," +
		"`traffic_time` datetime NOT NULL," +
		"`url` varchar(1024) NOT NULL DEFAULT ''," +
		"`refer` varchar(1024) NOT NULL DEFAULT ''," +
		"`visit` tinyint(4) NOT NULL," +
		"`ip` int(10) unsigned NOT NULL," +
		"`ip_count` int(11) NOT NULL DEFAULT '1'," +
		"`proxy_ip` varchar(255) NOT NULL DEFAULT ''," +
		"`ip_timezone` float(11,2) NOT NULL DEFAULT '0.00'," +
		"`is_badip` int(11) NOT NULL DEFAULT '0'," +
		"`is_bot` int(11) NOT NULL DEFAULT '0'," +
		"`country` varchar(4) NOT NULL DEFAULT ''," +
		"`city` varchar(20) NOT NULL DEFAULT ''," +
		"`client` varchar(510) NOT NULL DEFAULT ''," +
		"`ua` varchar(2048) NOT NULL DEFAULT ''," +
		"PRIMARY KEY (`id`)" +
		") ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;"
	system.Db.Query(TableSql)

	sql, err := db.Prepare("insert into `" + TableName + "` (ad_id,rules_id,publisher_id,rule_memo,traffic_time,url,refer,ip,visit,ip_count,proxy_ip,ip_timezone,is_badip,is_bot,country,city,client,ua) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
	utils.Chkerr(err)
	res, err1 := sql.Exec(ad_id, ruleid, publisher_id, rule_memo, times, url, refer, ip_int, visit, ip_count, 9, ip_zone, badip, 12, country, city, client, ua)
	utils.Chkerr(err1)
	id, err2 := res.LastInsertId()
	utils.Chkerr(err2)
	log.Println("save:", &res)
	return id
}

//查询缓存
func cacheSql(sql string) ([]map[string]interface{}, error) {
	cacheName := "sql:" + utils.Md5(sql)
	var data []map[string]interface{}

	v, err1 := redis.String(system.Redis.Do("GET", cacheName))
	utils.Chkerr(err1)
	if v != "" {
		json.Unmarshal([]byte(v), &data)
		return data, nil
	} else {
		rows, err := system.Db.Query(sql)
		utils.Chkerr(err)
		if err != nil {
			return nil, err
		}
		data = utils.SqlResolve(rows)
		jsonByte, _ := json.Marshal(data)
		jsonStr := string(jsonByte)
		system.Redis.Do("SETEX", cacheName, 300, jsonStr)
	}

	return data, nil
}

//统计IP
func CountIP(ip uint32) int {
	date := time.Now().Format("2006-01-02")
	TableName := "ads_traffic_" + date
	sql := fmt.Sprintf("select id from `"+TableName+"` where `ip` ='%d' and date(traffic_time) = date(NOW())", ip)
	res, err := system.Db.Query(sql)
	if err == nil {
		data := utils.SqlResolve(res)

		return len(data)
	}
	return 0
}
